<?php
namespace app\index\controller;

use think\Db;

class Index extends Common
{
    //页面主框架渲染
    public function index()
    {
        $msg = [
            'name' => SESSION('name'),
        ];
        $this->assign('msg', $msg);
        return $this->fetch();
    }

    //欢迎页渲染
    public function welcome()
    {
        //获取基础信息
        $info = Db('user')
            ->alias("user")
            ->join('base_info', 'user.id = base_info.user_id')
            ->join('filesalary_info', 'user.id = filesalary_info.user_id')
            ->join('realsalary_info', 'user.id = realsalary_info.user_id')
            ->join('company', 'base_info.company_id = company.id')
            ->where('user.job_number', '=', SESSION('jobNumber'))
            ->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

    // LAYUIMINI框架获取初始化数据
    public function getSystemInit()
    {
        $homeInfo = [
            'title' => '首页',
            'href' => '/index/index/welcome',
        ];
        $logoInfo = [
            'title' => '工资管理系统',
            'image' => '/static/images/logo.png',
        ];
        $menuInfo = $this->getMenuList();
        $systemInit = [
            'homeInfo' => $homeInfo,
            'logoInfo' => $logoInfo,
            'menuInfo' => $menuInfo,
        ];
        return json($systemInit);
    }

    // 获取菜单列表
    private function getMenuList()
    {
        //获取用户权限信息
        $auth = Db::name('auth')
            ->where('id', SESSION('role_id'))
            ->find();
        $menuList = Db::name('system_menu')
            ->field('id,pid,title,icon,href,target')
            ->where([
                'status' => ['=', '1'],
                'id' => ['in', $auth['auth']],
            ])
            ->order('sort', 'desc')
            ->select();
        $menuList = $this->buildMenuChild(0, $menuList);
        return $menuList;
    }

    //递归获取子菜单
    private function buildMenuChild($pid, $menuList)
    {
        $treeList = [];
        foreach ($menuList as $v) {
            if ($pid == $v['pid']) {
                $node = $v;
                $child = $this->buildMenuChild($v['id'], $menuList);
                if (!empty($child)) {
                    $node['child'] = $child;
                }
                // todo 后续此处加上用户的权限判断

                $treeList[] = $node;
            }
        }
        return $treeList;
    }
}
